
//1. 创建一个服务器
//有人登陆：看是谁记下来，两个人之间传话

async function startupCompiler() {
    const { createServer } = require('vite');
    const server = await createServer({
        // 任何合法的用户配置选项，加上 `mode` 和 `configFile`
        configFile: false,
        root: __dirname,
        server: {
            port: 3000
        }
    })
    await server.listen()

    server.printUrls()
}

async function startEditor() {

    const { app, BrowserWindow, BrowserView } = require('electron')

    function createWindow() {
        const editorProcess = new BrowserWindow({
            width: 800,
            height: 600,
            webPreferences: {
                nodeIntegration: true,  //允许渲染进程使用Nodejs
                contextIsolation: false //允许渲染进程使用Nodejs
            }
        })
        editorProcess.loadURL('http://localhost:3000/editor.html')
        //editorProcess.openDevTools();


        setTimeout(() => {
            const view2 = new BrowserView()
            editorProcess.setBrowserView(view2)
            view2.setBounds({ x: 100, y: 50, width: 400, height: 400 })
            view2.webContents.loadURL('http://localhost:3000/')
            //view2.webContents.openDevTools({ mode: 'undocked' })
        }, 2000)
    }

    app.whenReady().then(() => {
        createWindow();
        app.on('activate', () => {
            if (BrowserWindow.getAllWindows().length === 0) createRuntimeProcess()
        })

    })

    app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') app.quit()
    })
}

async function startup() {
    new WebSocketProxy().start();
    await startupCompiler();
    await startEditor();
}


class WebSocketProxy {

    editorClient
    runtimeClient;
    //启动服务器的方法
    start() {
        let self = this;
        //两个传消息
        const { Server } = require('ws');
        const wss = new Server({ port: 1234 });
        wss.on('connection', function connection(client) {
            client.on('message', function message(text) {
                const data = JSON.parse(text);
                console.log(data)
                if (data.command === 'login') {
                    if (data.id === 'editor') {
                        self.editorClient = client;
                    }
                    else if (data.id === 'runtime') {
                        self.runtimeClient = client;
                    }
                }
                else {
                    if (data.id === 'editor') {
                        self.runtimeClient.send(text);
                    }
                    else if (data.id === 'runtime') {
                        self.editorClient.send(text);
                    }
                }
            });
        });
    }
}


startup().catch(e => {
    console.log(e)
})



